package core

import (
	"context"
	"io"
	"net"
	"net/http"
	"sync"
	"time"
)

func _getClient(ipaddr string) http.Client {
	cil := http.Client{
		Transport: &http.Transport{
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				//本地地址  ipaddr是本地外网IP
				lAddr, err := net.ResolveTCPAddr(network, ipaddr+":0")
				if err != nil {
					return nil, err
				}
				//被请求的地址
				rAddr, err := net.ResolveTCPAddr(network, addr)
				if err != nil {
					return nil, err
				}
				conn, err := net.DialTCP(network, lAddr, rAddr)
				if err != nil {
					return nil, err
				}

				return conn, nil
			},
		},
	}
	return cil
}

//FlvPullStream ...
func FlvPullStream(address string, errCh chan<- int, over <-chan struct{}, wg *sync.WaitGroup) {
	defer wg.Done()
	req, _ := http.NewRequest("GET", address, nil)
	req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_	15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15")
	cli := &http.Client{}
	//cli := _getClient(ipaddr)
	resp, err := cli.Do(req)
	if err != nil {
		return
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)
	if resp.StatusCode != 200 {
		errCh <- resp.StatusCode
		return
	}
	b := make([]byte,  1024*1024)
	for {
		select {
		case <-over:
			return
		default:
			n, err := resp.Body.Read(b)
			if n >4096 {
				time.Sleep(time.Millisecond*1)
			}
			if err != nil {
				return
			}
		}
	}
}

//TestStream ...
func TestStream(address []string) (result bool, successUrl string) {
	for _, URL := range address {
		if len(URL) != 0 {
			b, s := func(_url string) (bool, string) {
				req, _ := http.NewRequest("GET", _url, nil)
				req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15")
				cli := &http.Client{}
				resp, err := cli.Do(req)
				if err != nil {
					return false, ""
				}
				defer func(Body io.ReadCloser) {
					_ = Body.Close()
				}(resp.Body)

				if resp.StatusCode == 200 {
					return true, URL
				} else {
					return false, ""
				}
			}(URL)
			if b {
				return true, s
			}
		}
	}
	return false, ""
}
